#!/bin/bash

# PGM PostgreSQL管理平台启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${2}${1}${NC}"
}

# 检查Go环境
check_go() {
    if ! command -v go &> /dev/null; then
        print_message "错误: Go未安装或不在PATH中" $RED
        exit 1
    fi
    
    GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    print_message "检测到Go版本: $GO_VERSION" $GREEN
}

# 检查PostgreSQL连接
check_postgres() {
    if command -v psql &> /dev/null; then
        print_message "检测到PostgreSQL客户端" $GREEN
    else
        print_message "警告: 未检测到PostgreSQL客户端，请确保数据库可访问" $YELLOW
    fi
}

# 安装依赖
install_deps() {
    print_message "正在安装Go依赖..." $BLUE
    go mod download
    print_message "依赖安装完成" $GREEN
}

# 构建项目
build_project() {
    print_message "正在构建项目..." $BLUE
    
    # 设置构建信息
    BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S')
    GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
    
    go build -ldflags "-X 'main.BuildTime=$BUILD_TIME' -X 'main.GitCommit=$GIT_COMMIT'" \
        -o pgm cmd/server/main.go
    
    print_message "构建完成" $GREEN
}

# 检查配置文件
check_config() {
    if [ ! -f "configs/config.yaml" ]; then
        print_message "警告: 配置文件不存在，将使用默认配置" $YELLOW
        
        # 创建默认配置目录
        mkdir -p configs
        
        # 如果配置文件不存在，询问是否创建
        read -p "是否创建默认配置文件? (y/n): " create_config
        if [ "$create_config" = "y" ] || [ "$create_config" = "Y" ]; then
            cat > configs/config.yaml << EOF
server:
  port: 8080
  host: localhost
  mode: debug

database:
  host: localhost
  port: 5432
  user: postgres
  password: ""
  dbname: ""
  sslmode: disable
  timezone: UTC

web:
  static_path: ./web/static
  template_path: ./web/templates

logging:
  level: info
  format: json

mapping:
  config_file: ./configs/table_mapping.yaml
EOF
            print_message "默认配置文件已创建" $GREEN
        fi
    fi
}

# 启动服务
start_server() {
    print_message "正在启动PGM服务..." $BLUE
    
    # 解析命令行参数
    ARGS=""
    while [[ $# -gt 0 ]]; do
        case $1 in
            --db|--database)
                ARGS="$ARGS -db $2"
                shift 2
                ;;
            --host|--dbhost)
                ARGS="$ARGS -dbhost $2"
                shift 2
                ;;
            --user|--dbuser)
                ARGS="$ARGS -dbuser $2"
                shift 2
                ;;
            --password|--dbpass)
                ARGS="$ARGS -dbpass $2"
                shift 2
                ;;
            --port)
                ARGS="$ARGS -port $2"
                shift 2
                ;;
            --config)
                ARGS="$ARGS -config $2"
                shift 2
                ;;
            *)
                print_message "未知参数: $1" $RED
                exit 1
                ;;
        esac
    done
    
    # 启动服务
    ./pgm $ARGS
}

# 显示帮助信息
show_help() {
    echo "PGM PostgreSQL管理平台启动脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --db, --database DB_NAME    数据库名称"
    echo "  --host, --dbhost HOST        数据库主机 (默认: localhost)"
    echo "  --user, --dbuser USER        数据库用户名 (默认: postgres)"
    echo "  --password, --dbpass PASS    数据库密码"
    echo "  --port PORT                  服务端口 (默认: 8080)"
    echo "  --config PATH                配置文件路径 (默认: ./configs)"
    echo "  -h, --help                   显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 --db myapp --user postgres --password mypass"
    echo "  $0 --db myapp --port 9090"
    echo ""
}

# 主函数
main() {
    print_message "=== PGM PostgreSQL管理平台 ===" $BLUE
    print_message "开始启动流程..." $GREEN
    
    # 处理帮助参数
    if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        show_help
        exit 0
    fi
    
    # 检查环境
    check_go
    check_postgres
    
    # 检查配置
    check_config
    
    # 如果可执行文件不存在，则构建
    if [ ! -f "pgm" ]; then
        install_deps
        build_project
    else
        print_message "发现已存在的可执行文件" $GREEN
    fi
    
    # 启动服务
    start_server "$@"
}

# 运行主函数
main "$@"